<?php 

class Flags extends CI_Model {

    function __construct()
    {
        // Call the Model constructor
        parent::__construct();
    }
    function all_flag_types()
    {
        $query = $this->db->get('flag_type');
        return $query->result();
    }
	function get_flag_event_type_data($id)
	{
		$query = $this->db->from('flag_event_type')
						->where('idflag_event_type', $id)
						->get();
        
		if(count($query->result()) == 1)
		{
			$res = $query->result();
			return $res[0];
		}
		else
		{
			throw new Exception('Unknown flag event type id = ' . $id);
		}
	}	
	
	function get_flag_type_data($id_or_name)
	{
		if(is_numeric($id_or_name))
		{
			$query = $this->db->from('flag_type')
							->where('idflag_type', $id_or_name)
							->get();
		}
		else
		{
			$query = $this->db->from('flag_type')
							->where('name', $id_or_name)
							->get();
		}
        
		if(count($query->result()) == 1)
		{
			$res = $query->result();
			return $res[0];
		}
		else
		{
			throw new Exception('Unknown flag type id = ' . $id_or_name);
		}
	}
	
	function get_users_flags($user)
	{
		$query = $this->db->from('flag')
							->join('flag_type', 'flag.idflag_type = flag_type.idflag_type')
							->join('articles', 'flag.idarticle = articles.idarticle')
							->join('flag_states', 'flag.idflag_states = flag_states.idflag_states')
							->where('iduser_flagger = ', $user->iduser)
							->get();
		$users_flags = $query->result();
		
		foreach($users_flags as $users_flag)
		{
			$query = $this->db->from('flag_event')
								->join('flag_event_type', 'flag_event.idflag_event_type = flag_event_type.idflag_event_type')
								->where('idflag = ', $users_flag->idflag)
								->get();
			$users_flag->events = $query->result();
			
			$users_flag->latest_event = $users_flag->events[count($users_flag->events) - 1];
			
			$query = $this->db->from('flag_event_type')
				->where('idflag_event_type in ('. $users_flag->next_event_flagger .')')
				->order_by('order', "asc")
				->get();
		
			$users_flag->next_actions = $query->result();
		}
		
		return $users_flags;
	}
}